package com.web.exiaodao.remote.service.impl;

import com.alibaba.fastjson.JSON;
import com.web.exiaodao.business.constant.JConstant;
import com.web.exiaodao.business.entity.MakeMoneyTable;
import com.web.exiaodao.business.entity.User;
import com.web.exiaodao.business.repository.MakeMoneyTableRepository;
import com.web.exiaodao.business.repository.UserRepository;
import com.web.exiaodao.business.service.MakeMoneyTableService;
import com.web.exiaodao.remote.service.ApiConfigurationTableService;
import com.web.exiaodao.remote.service.ApiMakeMoneyTableService;
import com.web.exiaodao.remote.service.ApiUserService;
import com.web.exiaodao.remote.vo.ConfigurationTableVo;
import com.web.exiaodao.remote.vo.UserVo;
import com.web.webstart.base.constant.XaConstant;
import com.web.webstart.base.exception.BusinessException;
import com.web.webstart.base.service.impl.BaseService;
import com.web.webstart.base.util.XaUtil;
import com.web.webstart.base.util.encryptDir.MD5Util;
import com.web.webstart.base.util.jpa.DynamicSpecifications;
import com.web.webstart.base.util.jpa.SearchFilter;
import com.web.webstart.base.util.jpa.SearchFilter.Operator;
import com.web.webstart.base.util.result.XaResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author: zhangl
 * @times: 2015-5-15下午06:46:35
 * 类的说明：前端APIUser接口实现类
 **/
@Service("ApiUserService")
@Transactional(readOnly = false)
public class ApiUserServiceImpl extends BaseService<User> implements ApiUserService {

    @Autowired
    UserRepository userRepository;

    @Autowired
    MakeMoneyTableService makeMoneyTableService;

    @Autowired
    ApiMakeMoneyTableService apiMakeMoneyTableService;

    @Autowired
    ApiConfigurationTableService configurationTableService;

    @Autowired
    JdbcTemplate jdbcTemplate;
    
    @Autowired
    MakeMoneyTableRepository makeMoneyTableRepository;

    /**
     * 接口返回所有的和用户相关的信息;(亲币..)
     * @param tId
     * @return
     * @throws BusinessException
     */
    @Override
    public XaResult<UserVo> findOne(Long tId) throws BusinessException {
        User obj = userRepository.findByIdAndStatusNot(tId, XaConstant.Status.delete);
        XaResult<UserVo> xr = new XaResult<UserVo>();
        if (XaUtil.isNotEmpty(obj)) {
            xr.setObject(JSON.parseObject(JSON.toJSONString(obj), UserVo.class));
            xr.getObject().setId(obj.getId());
            //计算总的亲币
           XaResult<Integer> countMoneyXr = makeMoneyTableService.calculateMoney(tId);
            xr.getObject().setBalanceCoin(Double.parseDouble(countMoneyXr.getObject()+""));
            //获取配置表信息
            ConfigurationTableVo configVo = configurationTableService.findLastOne().getObject();
            xr.getObject().setConfigurationVo(configVo);
        } else {
            throw new BusinessException(XaConstant.Message.object_not_find);
        }
        return xr;
    }

    @Override
    public XaResult<List<UserVo>> findListNEStatusByFilter(
            Integer status, Map<String, Object> filterParams, Pageable pageable)
            throws BusinessException {
        Map<String, SearchFilter> filters = SearchFilter.parse(filterParams);
        if (status == null) {// 默认显示非删除的所有数据
            status = XaConstant.Status.delete;
        }
        filters.put("status", new SearchFilter("status", Operator.NE, status));
        Page<User> page = userRepository.findAll(DynamicSpecifications
                .bySearchFilter(filters.values(), User.class), pageable);
        XaResult<List<UserVo>> xr = new XaResult<List<UserVo>>();
        xr.setObject(JSON.parseArray(JSON.toJSONString(page.getContent()), UserVo.class));
        for (int i = 0; i < page.getContent().size(); i++) {
            xr.getObject().get(i).setId(page.getContent().get(i).getId());
        }
        return xr;
    }

    @Override
    public XaResult<List<UserVo>> findListEQStatusByFilter(
            Integer status, Map<String, Object> filterParams, Pageable pageable)
            throws BusinessException {
        Map<String, SearchFilter> filters = SearchFilter.parse(filterParams);
        if (status == null) {// 默认显示正常数据
            status = XaConstant.Status.valid;
        }
        filters.put("status", new SearchFilter("status", Operator.EQ, status));
        Page<User> page = userRepository.findAll(DynamicSpecifications
                .bySearchFilter(filters.values(), User.class), pageable);
        XaResult<List<UserVo>> xr = new XaResult<List<UserVo>>();
        xr.setObject(JSON.parseArray(JSON.toJSONString(page.getContent()), UserVo.class));
        for (int i = 0; i < page.getContent().size(); i++) {
            xr.getObject().get(i).setId(page.getContent().get(i).getId());
        }
        return xr;
    }

    @Override
    public XaResult<UserVo> multiOperate(String modelIds,
                                         Integer status) throws BusinessException {
        XaResult<UserVo> xr = new XaResult<UserVo>();
        if (status == null) {
            status = XaConstant.Status.delete;
        }
        if (modelIds != null) {
            String[] ids = modelIds.split(",");
            for (String id : ids) {
                User obj = userRepository.findByIdAndStatusNot(Long.parseLong(id), status);
                if (XaUtil.isNotEmpty(obj)) {
                    obj.setStatus(status);
                    obj = userRepository.save(obj);
                    xr.setObject(JSON.parseObject(JSON.toJSONString(obj), UserVo.class));
                    xr.getObject().setId(obj.getId());
                } else {
                    throw new BusinessException(XaConstant.Message.object_not_find);
                }
            }
        }
        return xr;
    }

    @Override
    public XaResult<UserVo> createModel(User model)
            throws BusinessException {
        XaResult<UserVo> xr = new XaResult<UserVo>();
        //设置默认的昵称
        String mobile = model.getMobile();
        //180****1390
        String nickName = mobile.substring(0,3) + "****" + mobile.substring(7);
        model.setUserName(nickName);

        User obj = userRepository.save(model);
        xr.setObject(JSON.parseObject(JSON.toJSONString(obj), UserVo.class));
        xr.getObject().setId(obj.getId());

        //获取配置表信息
        ConfigurationTableVo configVo = configurationTableService.findLastOne().getObject();
        //赚钱表添加一条数据
        XaResult<MakeMoneyTable> makeMoneyXR = apiMakeMoneyTableService.saveMakeMoneyRecord(obj.getId(), JConstant.ConsumeOrMakeMoney.MakeMoney, configVo.getIncome_register_coin() , JConstant.IntegralTypeEnum.REGISTER.getIndex());

        //推荐人增加亲币
        if (XaUtil.isNotEmpty(model.getRecommendPhone())) {
            User reUser = userRepository.findByMobile(model.getRecommendPhone());
            if (reUser == null || XaUtil.isEmpty(reUser.getMobile())) {
                xr.error("该推荐人不存在!");
                return xr;
            }
            if (reUser.getStatus() == XaConstant.Status.locked) {
                xr.error("推荐人账号已经停用，请联系管理员", new UserVo());
                return xr;
            }
            if (reUser.getStatus() == XaConstant.Status.delete) {
                xr.error("推荐人账号已经被删除，请联系管理员", new UserVo());
                return xr;
            }
            apiMakeMoneyTableService.saveMakeMoneyRecord(reUser.getId(), JConstant.ConsumeOrMakeMoney.MakeMoney, configVo.getIncome_recommend_coin() , JConstant.IntegralTypeEnum.RECOMMEND_USER.getIndex());
        }
        return xr;
    }

    @Override
    public XaResult<UserVo> updateModel(User model)
            throws BusinessException {
        User obj = userRepository.findOne(model.getId());
        XaResult<UserVo> xr = new XaResult<UserVo>();
        if (XaUtil.isNotEmpty(obj)) {
            obj.setUserName(XaUtil.isNotEmpty(model.getUserName()) ? model.getUserName() : obj.getUserName());
            obj.setPassword(XaUtil.isNotEmpty(model.getPassword()) ? model.getPassword() : obj.getPassword());
            obj.setMobile(XaUtil.isNotEmpty(model.getMobile()) ? model.getMobile() : obj.getMobile());
            obj.setPhoto(XaUtil.isNotEmpty(model.getPhoto()) ? model.getPhoto() : obj.getPhoto());
            obj.setMemo(XaUtil.isNotEmpty(model.getMemo()) ? model.getMemo() : obj.getMemo());
            obj.setBirthday(XaUtil.isNotEmpty(model.getBirthday()) ? model.getBirthday() : obj.getBirthday());
            obj.setPayPassword(XaUtil.isNotEmpty(model.getPayPassword()) ? model.getPayPassword() : obj.getPayPassword());
            obj.setAlipayAccount(XaUtil.isNotEmpty(model.getAlipayAccount()) ? model.getAlipayAccount() : obj.getAlipayAccount());
            obj.setBalance(XaUtil.isNotEmpty(model.getBalance()) ? model.getBalance() : obj.getBalance());
            obj.setVip(XaUtil.isNotEmpty(model.getVip()) ? model.getVip() : obj.getVip());
            obj.setVipOrderNo(XaUtil.isNotEmpty(model.getVipOrderNo()) ? model.getVipOrderNo() : obj.getVipOrderNo());
            obj.setEmail(XaUtil.isNotEmpty(model.getEmail()) ? model.getEmail() : obj.getEmail());
            obj = userRepository.save(obj);
            xr.setObject(JSON.parseObject(JSON.toJSONString(obj), UserVo.class));
            xr.getObject().setId(obj.getId());
        } else {
            throw new BusinessException(XaConstant.Message.object_not_find);
        }
        return xr;
    }

    @Override
    public User validMobile(String mobile) {
        return userRepository.findTopByMobileAndStatusNot(mobile, XaConstant.Status.delete);
    }

    @Override
    public User validUserId(String userId) {
        return userRepository.findByIdAndStatusNot(Long.parseLong(userId),  XaConstant.Status.delete);
    }

    @Override
    public User validUserName(String userName) {
        return userRepository.findByUserNameAndStatusNot(userName, XaConstant.Status.delete);
    }

    @Override
    public XaResult<UserVo> login(String mobile, String password)  throws BusinessException {
        XaResult<UserVo> xr = new XaResult<>();
        User user = userRepository.findTopByMobileAndStatusNot(mobile, XaConstant.Status.delete);
        //根据推荐人手机号查询该用户
        if (XaUtil.isEmpty(user)) {
            xr.error("你的账户不存在", new UserVo());
            return xr;
        }
        if (XaUtil.isNotEmpty(user)) {
            if (user.getStatus() == XaConstant.Status.locked) {
                xr.error("你账户已经停用，请联系管理员", new UserVo());
                return xr;
            }
            if (user.getStatus() == XaConstant.Status.delete) {
                xr.error("你账户已经被删除，请联系管理员", new UserVo());
                return xr;
            }
            if (!MD5Util.getMD5String(password).equals(user.getPassword())) {
                xr.error("密码错误！");
                return xr;
            }
            xr.success(JSON.parseObject(JSON.toJSONString(user), UserVo.class));
        } else {
            xr.error("用户不存在", new UserVo());
            return xr;
        }
        //获取配置表信息
        ConfigurationTableVo configVo = configurationTableService.findLastOne().getObject();
        xr.getObject().setConfigurationVo(configVo);

        return xr;
    }

    @Override
    public XaResult<UserVo> updatePwd(Long id, String oldpassword, String newpassword) {
        User obj = userRepository.findOne(id);
        XaResult<UserVo> xr = new XaResult<UserVo>();
        if (XaUtil.isNotEmpty(obj)) {
            //判断原密码是否相同
            if (!MD5Util.getMD5String(oldpassword).equals(obj.getPassword())) {
                xr.error("原密码不正确");
                return xr;
            }
            obj.setPassword(MD5Util.getMD5String(newpassword));
            obj = userRepository.save(obj);
            xr.setObject(JSON.parseObject(JSON.toJSONString(obj), UserVo.class));
            xr.getObject().setId(obj.getId());
        } else {
            xr.error("该用户不存在");
        }
        return xr;
    }

    @Override
    public XaResult<UserVo> forgetPwd(String mobile, String newpassword) {
        XaResult<UserVo> xr = new XaResult<UserVo>();
        User user = new User();
        if (XaUtil.isNotEmpty(mobile)) {
            user = userRepository.findTopByMobileAndStatusNot(mobile, XaConstant.Status.delete);
            if (XaUtil.isEmpty(user)) {
                xr.error("该手机尚未注册");
                return xr;
            }
        }
        user.setPassword(MD5Util.getMD5String(newpassword));
        user = userRepository.save(user);
        xr.setObject(JSON.parseObject(JSON.toJSONString(user), UserVo.class));
        xr.getObject().setId(user.getId());
        return xr;
    }

    @Override
    public XaResult<UserVo> forgetPayPwd(String mobile, String newpassword) {
        XaResult<UserVo> xr = new XaResult<UserVo>();
        User user = new User();
        if (XaUtil.isNotEmpty(mobile)) {
            user = userRepository.findTopByMobileAndStatusNot(mobile, XaConstant.Status.delete);
            if (XaUtil.isEmpty(user)) {
                xr.error("该手机尚未注册");
                return xr;
            }
        }
        user.setPayPassword(newpassword);
        user = userRepository.save(user);
        xr.setObject(JSON.parseObject(JSON.toJSONString(user), UserVo.class));
        xr.getObject().setId(user.getId());
        return xr;
    }

    @Override
    public XaResult<UserVo> updatePayPwd(Long id, String oldpassword, String newpassword) {
        User obj = userRepository.findOne(id);
        XaResult<UserVo> xr = new XaResult<UserVo>();
        if (XaUtil.isNotEmpty(obj)) {
            //判断原密码是否相同
            if (!oldpassword.equals(obj.getPayPassword())) {
                xr.error("原密码不正确");
                return xr;
            }
            obj.setPayPassword(newpassword);
            obj = userRepository.save(obj);
            xr.setObject(JSON.parseObject(JSON.toJSONString(obj), UserVo.class));
            xr.getObject().setId(obj.getId());
        } else {
            xr.error("该用户不存在");
        }
        return xr;
    }

    //根据推荐人手机号查询用户（三级）
	@Override
	public XaResult<List<UserVo>> findUserList(String recommendPhone)
			throws BusinessException {
//		SELECT * FROM (
//				SELECT * FROM `tb_xa_user` WHERE recommend_phone = '18049531390'  AND STATUS<>3
//				) t1
//				UNION 
//				SELECT * FROM `tb_xa_user` WHERE recommend_phone IN (
//				SELECT mobile FROM `tb_xa_user` WHERE recommend_phone = '18049531390'
//				) AND STATUS<>3
		StringBuffer sql = new StringBuffer("SELECT * FROM (SELECT * FROM `tb_xa_user` WHERE recommend_phone ='").append(recommendPhone).append("' AND STATUS<>3 ) t1");
		sql.append(" UNION SELECT * FROM `tb_xa_user` WHERE recommend_phone IN ( SELECT mobile FROM `tb_xa_user` WHERE recommend_phone = '").append(recommendPhone).append("' ) AND STATUS<>3 ");
		List<Object[]> objs = this.query(sql.toString(), null,null);
		List<UserVo> vos = new ArrayList<UserVo>();
		for (Object[] obj : objs) {
			UserVo vo = new UserVo();
			vo.setId(Long.valueOf(obj[0].toString()));
			vo.setCreateTime(XaUtil.isEmpty(obj[1])?"":obj[1].toString());
			vo.setStatus(XaUtil.isEmpty(obj[3])?0:Integer.valueOf(obj[3].toString()));
			vo.setBirthday(XaUtil.isEmpty(obj[4])?"":obj[4].toString());
			vo.setMemo(XaUtil.isEmpty(obj[5])?"":obj[5].toString());
			vo.setMobile(XaUtil.isEmpty(obj[6])?"":obj[6].toString());
			vo.setPhoto(XaUtil.isEmpty(obj[9])?"":obj[9].toString());
			vo.setUserName(XaUtil.isEmpty(obj[10])?"":obj[10].toString());
			vo.setBalanceCoin(XaUtil.isEmpty(obj[11])?0:Double.valueOf(obj[11].toString()));
			vo.setRecommendPhone(XaUtil.isEmpty(obj[12])?"":obj[12].toString());
			vos.add(vo);
		}
		XaResult<List<UserVo>> xr = new XaResult<List<UserVo>>();
		xr.setObject(vos);
		return xr;
	}
}
